package com.dataextend.config.exception;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/*
 * 全局异常处理器
 * */
@ControllerAdvice
@ResponseBody
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> handleException(Exception e) {
        e.printStackTrace();
        return onResponse(500, "服务器内部错误");
    }

    /*
     * shiro 权限认证不过抛异常
     * */
    @ExceptionHandler(value = UnauthorizedException.class)
    public Map<String, Object> handleUnauthorizedException(UnauthorizedException ue) {
        return onResponse(403, "用户权限不足");
    }

    /*
     * 统一返回格式
     * */
    private Map<String, Object> onResponse(int code, String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }
}
